//
//  VVYLocation.m
//  唯唯游
//
//  Created by Jay_Apple on 15/10/8.
//  Copyright (c) 2015年 weiweiyou. All rights reserved.
//

#import "VVYLocationManager.h"
#import <MapKit/MapKit.h>
#import "VVYChangeCoordinate.h"

typedef enum : NSUInteger {
    MapTypeApple,
    MapTypeBaidu,
    MapTypeGaode,
} MapType;


@interface VVYLocationManager () <CLLocationManagerDelegate>

@property (nonatomic, strong)CLLocationManager *manager;


@property (nonatomic, strong)locationSuccess success;

@property (nonatomic, strong)locationFauilre failure;

@property (nonatomic, copy, readwrite) NSString *city;

@property (nonatomic, copy, readwrite) NSString *area;

@property (nonatomic, assign, readwrite) CLLocationCoordinate2D locCoordinate;

@property (nonatomic, assign) MapType type;

@property (nonatomic, strong) MKMapView *mapView;

@property(nonatomic,strong)CLGeocoder *geocoder;

@end


@implementation VVYLocationManager
/**
 *  单例
 */
static id _instance;

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    @synchronized(self) {
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];
        }
    }
    return _instance;
}

+ (instancetype)sharedManager
{
    @synchronized(self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}

- (id)copyWithZone:(NSZone *)zone
{
    return _instance;
}

//初始化方法
- (void)getLocationCityInfoSuccess:(locationSuccess)success failure:(locationFauilre)failure{
     
    self.success = success;
    self.failure = failure;
    [self locate];
}

- (void)stopLocation{

    self.success = nil;
    self.failure = nil;
    [self.manager stopUpdatingLocation];
}


#pragma mark - 懒加载
/**
 *  Locationmanger
 */
- (CLLocationManager *)manager{
    
    if (_manager == nil) {
        _manager = [[CLLocationManager alloc] init];
        _manager.desiredAccuracy = kCLLocationAccuracyBest;
        _manager.distanceFilter = 10.0f;
        _manager.delegate = self;
//        [_manager requestAlwaysAuthorization];//添加这句
        [_manager requestWhenInUseAuthorization];
    }
    return _manager;
}

/**
 *  地里编码
 */
-(CLGeocoder *)geocoder
{
    if (_geocoder==nil) {
        _geocoder=[[CLGeocoder alloc]init];
    }
    return _geocoder;
}

/**
 *  mapView（定位）
 */
- (MKMapView *)mapView{
    
    if (_mapView == nil) {
        MKMapView *mapView =[[MKMapView alloc] init];
        
        _mapView = mapView;
    }
    
    return _mapView;
}

//定位
- (void)locate{
    
    // 判断定位操作是否被允许
    
    if(![CLLocationManager locationServicesEnabled]) {
        //提示用户无法进行定位操作
    
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:
                                  
                                  @"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
    }
    
    
        //??这样的顺序，将导致bug：第一次启动程序后，系统将只请求?的权限，?的权限系统不会请求，只会在下一次启动应用时请求?
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8) {
            [_manager requestWhenInUseAuthorization];//?只在前台开启定位
//            [self.manager requestAlwaysAuthorization];//?在后台也可定位
        }
        // 5.iOS9新特性：将允许出现这种场景：同一app中多个location manager：一些只能在前台定位，另一些可在后台定位（并可随时禁止其后台定位）。
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
//            self.manager.allowsBackgroundLocationUpdates = YES;
        }
        // 6. 更新用户位置
        [self.manager startUpdatingLocation];
        
    
}

#pragma mark - CoreLocation Delegate



-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations

{
    
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    
    [manager stopUpdatingLocation];
    
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    
    CLLocation *currentLocation = [locations lastObject];
    
    // 获取当前所在的城市名
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //根据经纬度反向地理编译出地址信息
    __weak typeof(self) weakSelf = self;
    
    
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     
     {
         
         if (array.count > 0)
             
         {
             
             CLPlacemark *placemark = [array objectAtIndex:0];
             
             //获取区
             weakSelf.city = placemark.locality;
            weakSelf.area = placemark.subLocality;
             weakSelf.locCoordinate = currentLocation.coordinate;
//              weakSelf.city = [weakSelf.city substringToIndex:weakSelf.city.length - 1];
             if (!weakSelf.city) {
                 
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 
                weakSelf.city = placemark.administrativeArea;
                
                 
             }
             
             //调用成功block
             if (weakSelf.success) {
                 weakSelf.success(weakSelf.area, currentLocation.coordinate);
             }
             
         }
         
         else
             
         {
             if (weakSelf.failure) {
                 weakSelf.failure(@"定位失败");
             }
             
             
         }

     }];

    
}

//- (void)locationManager:(CLLocationManager *)manager
//
//       didFailWithError:(NSError *)error {
//    
//    if (self.failure) {
//        self.failure(@"定位失败");
//    }
//    
//    [manager stopUpdatingLocation];
//
//}

/**
 *  导航选择
 */
- (void)guideWithPlaceName:(NSString *)name{
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"使用苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.type = MapTypeApple;
        [self gerogeWithPlaceName:name];
    }];
    
    [alert addAction:action];
    
    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]){
        UIAlertAction *actionBaidu = [UIAlertAction actionWithTitle:@"使用百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            self.type = MapTypeBaidu;
            [self gerogeWithPlaceName:name];
            
            
        }];
        
        [alert addAction:actionBaidu];
    }
    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"iosamap://"]]){
        
        UIAlertAction *actionGaode = [UIAlertAction actionWithTitle:@"使用高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.type = MapTypeGaode;
            [self gerogeWithPlaceName:name];
        }];
        
        
        
        [alert addAction:actionGaode];
        
        
    }
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action2];
    
    
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    [vc presentViewController:alert animated:YES completion:nil];
    
}


/**
 *  根据经纬度导航
 */
- (void)guideWithCoordinate:(CLLocationCoordinate2D )coordinate{
    
    
    //百度坐标转换火星坐标（针对VVY项目）
    double lat = coordinate.latitude;
    double lon = coordinate.longitude;
    
    double changeLat;
    double changeLon;
    
    bd_decrypt(lat, lon, &changeLat, &changeLon);
    
    coordinate.latitude = changeLat;
    coordinate.longitude = changeLon;
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"使用苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self.type = MapTypeApple;
        [self startGuideWithEndCoor:coordinate];
    }];
    
    [alert addAction:action];
    
    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]){
        UIAlertAction *actionBaidu = [UIAlertAction actionWithTitle:@"使用百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            self.type = MapTypeBaidu;
             [self startGuideWithEndCoor:coordinate];
            
            
        }];
        
        [alert addAction:actionBaidu];
    }
    if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"iosamap://"]]){
        
        UIAlertAction *actionGaode = [UIAlertAction actionWithTitle:@"使用高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.type = MapTypeGaode;
             [self startGuideWithEndCoor:coordinate];
        }];
        
        
        
        [alert addAction:actionGaode];
        
        
    }
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action2];
    
    
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    [vc presentViewController:alert animated:YES completion:nil];
    
}



/**
 *  根据经纬度导航
 */
- (void)startGuideWithEndCoor:(CLLocationCoordinate2D )endCoor{
    
    switch (self.type) {
        case MapTypeApple:{
            
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:endCoor addressDictionary:nil]];
            toLocation.name = @"中国广东省广州市天河区中山大道西293";
            
            [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                           launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
            
        }
            break;
        case MapTypeGaode:
        {
            CGFloat endLat = endCoor.latitude;
            CGFloat endLon = endCoor.longitude;
            
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&poiname=%@&lat=%f&lon=%f&dev=0&style=2",@"VPrice", @"mapVprcie", @"终点", endLat, endLon] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
            
        }
            break;
        case MapTypeBaidu:
        {
            
            CLLocationCoordinate2D currentLocation = self.mapView.userLocation.location.coordinate;
            CGFloat currentLat = currentLocation.latitude;
            CGFloat currentLon = currentLocation.longitude;
            double endLat = endCoor.latitude;
            double endLon = endCoor.longitude;
            
            double BeginLat;
            double BeginLon;
            
            double EndLat;
            double EndLon;
            
            bd_encrypt(currentLat, currentLon, &BeginLat, &BeginLon);
            bd_encrypt(endLat, endLon, &EndLat, &EndLon);
            
            
            NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin=latlng:%f,%f|name:我的位置&destination=latlng:%f,%f|name:终点&mode=driving",BeginLat, BeginLon,EndLat,EndLon] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ;
            
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString]];
            
            
        }
            break;
            
        default:
            
            break;
    }
    
    
}


- (void)gerogeWithPlaceName:(NSString *)name{
    //1.获得输入的地址
    NSString *address=name;
    if (address.length==0) return;
    
    //2.开始地理编码
    //说明：调用下面的方法开始编码，不管编码是成功还是失败都会调用block中的方法
    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        //如果有错误信息，或者是数组中获取的地名元素数量为0，那么说明没有找到
        if (error || placemarks.count==0) {
            //NSlog(@"你输入的地址没找到，可能在月球上");
        }else   //  编码成功，找到了具体的位置信息
        {
            //打印查看找到的所有的位置信息
            /*
             61                     name:名称
             62                     locality:城市
             63                     country:国家
             64                     postalCode:邮政编码
             65                  */
            for (CLPlacemark *placemark in placemarks) {
                //NSlog(@"name=%@ locality=%@ country=%@ postalCode=%@",placemark.name,placemark.locality,placemark.country,placemark.postalCode);
            }
            
            //取出获取的地理信息数组中的第一个显示在界面上
            CLPlacemark *firstPlacemark=[placemarks firstObject];
            //详细地址名称
            //NSlog(@"%@",firstPlacemark.name) ;
            //纬度
            CLLocationDegrees latitude=firstPlacemark.location.coordinate.latitude;
            //经度
            CLLocationDegrees longitude=firstPlacemark.location.coordinate.longitude;
            
            
            [self startGuideWithEndCoor:CLLocationCoordinate2DMake(latitude, longitude)];
        }
    }];
}


- (NSString *)base64StringFromText:(NSString *)text
{
    
    NSData *nsdataFromBase64String = [[NSData alloc]
                                      initWithBase64EncodedString:text options:0];
    
    // Decoded NSString from the NSData
    NSString *base64Decoded = [[NSString alloc]
                               initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];
    //NSlog(@"resulit%@",base64Decoded);
    
    return base64Decoded;
}




@end
